package com.example.login.mvvm.view.activity

import android.Manifest
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.login.R
import com.example.login.mvvm.viewmodel.LoginViewModel
import com.gsafety.libraryktx.base.BaseActivity
import com.gsafety.libraryktx.bean.LoadState
import com.gsafety.libraryktx.config.Constant
import com.gsafety.libraryktx.core.RouterConstants
import com.gsafety.libraryktx.expand.create
import com.gsafety.libraryktx.expand.toast
import com.gsafety.libraryktx.manager.UserManager
import com.gsafety.libraryktx.util.AppUtil
import com.gsafety.libraryktx.util.FileUtils
import com.gsafety.libraryktx.util.StatusUtils
import kotlinx.android.synthetic.main.login_activity_login.*
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

/**
 * @author : lj
 * @date : 2020/9/15 10:59
 */
@Route(path = RouterConstants.LOGIN_ACTIVITY)
class LoginActivity : BaseActivity(),EasyPermissions.PermissionCallbacks,View.OnClickListener {
    private lateinit var mv: LoginViewModel
    private val PERMISSION = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA
    )
    override fun initView() {
        mv = LoginViewModel()
        mv = create(LoginViewModel::class)
        UserManager.getInstance().getUser()?.also {
            jumpMainPage()
        }
    }

    override fun initData() {
        login.setOnClickListener(this)
        if (EasyPermissions.hasPermissions(this, *PERMISSION)) {
            FileUtils.createOrExistsDir(Constant.CACHE_DIR)
        } else {
            requestPermission()
        }
        mv.loadState.observe(this, Observer {
            when (it) {
                is LoadState.Success -> {
                    disDia()
                    var login=UserManager.getInstance().getUser()
                    login?.let {
                        bean->
                        bean.passWord=et_password.text.toString().trim()
                        UserManager.getInstance().putLogin(bean)
                    }
                    jumpMainPage()
                }
                is LoadState.Fail -> {
                    disDia()
                    toast(it.msg)
                }
            }
        })

    }

    override fun getLayoutId(): Int {
        return R.layout.login_activity_login
    }

    override fun statusBar() {
        StatusUtils.transparentStatusBar(this)
    }

    private fun checkData(): Boolean {
        var flag = true
        var name = et_username.text.toString()
        var password = et_password.text.toString()
        if (name.isNullOrEmpty()) {
            flag = false
            toast("请输入您的用户名")
        } else if (password.isNullOrEmpty()) {
            flag = false
            toast("请输入您的登录密码")
        }
        return flag
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.login -> {
                if (checkData()) {
                    showDia(null)
                    var name = et_username.text.toString().trim()
                    var password = et_password.text.toString().trim()
                    mv.requestlogin(name,password)
                }
            }
        }
    }


    private fun requestPermission() {
        EasyPermissions.requestPermissions(this, "请设置权限", 1, *PERMISSION)
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            val builder = AppSettingsDialog.Builder(this)
            builder.setRationale("需要权限，请到设置中为应用程序打开所需权限")
            builder.setTitle("权限请求")
            builder.build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        FileUtils.createOrExistsDir(Constant.CACHE_DIR)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun handBack(): Boolean {
        AppUtil.appExit()
        return false
    }

    /**
     * 跳到首页
     */
    private fun jumpMainPage() {
        ARouter.getInstance().build(RouterConstants.MAIN_ACTIVITY).navigation()
        finish()
    }
}